<template>
  <div class="container">
    <div class="search width-1000">
      <p class="search-title fz20">
        搜索关键字: <span>{{ keywordTitle }}</span>
      </p>
      <div class="search-list" v-if="articleList.length">
        <ArticleList :articleList="articleList" :keyword="keywordTitle" :is_search="true" />
        <!-- 分页 -->
        <el-pagination
          v-if="pagination.total !== 0"
          background
          layout="prev, pager, next"
          :total="pagination.total"
          class="pagination"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
      <div class="empty" v-else>
        <p>暂无文章</p>
      </div>
    </div>
  </div>
</template>

<script>
import { getArticleList } from '@/api/article'
export default {
  name: 'Search',
  data() {
    return {
      articleList: [],
      pagination: {
        pageSize: 10,
        pageNumber: 1,
        total: 0,
        totalPages: 0
      }
    }
  },
  created() {
    this.getUserArticleList()
  },
  computed: {
    keywordTitle() {
      return this.$route.query.keyword
    }
  },
  watch: {
    // 对路由变化作出响应,当使用路由参数时，例如从 /user/foo 导航到 /user/bar，原来的组件实例会被复用,
    $route() {
      this.pagination.pageNumber = 1
      this.getUserArticleList()
    }
  },
  methods: {
    // 获取文章列表
    async getUserArticleList() {
      try {
        let params = {
          pageSize: this.pagination.pageSize,
          pageNumber: this.pagination.pageNumber,
          keyword: this.keywordTitle
        }
        const res = await getArticleList(params)
        if (res.code === 200) {
          this.articleList = res.data.list
          this.pagination = res.data.pagination
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 翻页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pagination.pageNumber = val
      this.getArticleList()
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  height: 100vh;
  border-top: 1px solid #f2f3f5;
  background-color: #f2f3f5;
  .search {
    margin-top: 80px;
    background-color: #fff;
    .search-title {
      margin-left: 20px;
    }
  }
  .search-title {
    padding-top: 10px;
    span {
      color: red;
    }
  }
}
.pagination {
  margin-top: 10px;
  padding-bottom: 10px;
}
</style>
